package com.feijia.aijingjingus;

import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.feijia.aijingjingus.entity.Mail;
import com.feijia.aijingjingus.request.SetMailRequest;
import com.feijia.aijingjingus.util.PreferencesUtils;
import com.feijia.aijingjingus.util.RetrofitUtil;
import com.feijia.aijingjingus.view.PhoneCode;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.md5;

public class MailSignupCodeActivity extends AppCompatActivity {
    TextView tv_mial, tv_Countdown;
    PhoneCode phoneCode;
    String Verification_Code;
    Retrofit retrofit;
    String toMail,Password="5438**#";
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mail_signup_code);
        initView();

    }

    public void onClickBack(View view) {
        finish();
    }

    private void initView() {
        toMail = PreferencesUtils.getString(getApplicationContext(), Constants.MAIL);
        Verification_Code = getFourRandom();
        tv_mial = (TextView) findViewById(R.id.tv_mial);
        tv_Countdown = (TextView) findViewById(R.id.tv_Countdown);
        phoneCode = (PhoneCode) findViewById(R.id.phonecode);
        getCode(Verification_Code);
        tv_mial.setText(getString(R.string.send_to_mailbox) + toMail);
        timer.start();
    }

    /**
     * 点击登陆验证验证码是否正确
     */
    public void login(View view) {

        if (!phoneCode.getPhoneCode().toString().isEmpty()) {
            if (phoneCode.getPhoneCode().toString().equals(Verification_Code)) {
                signup();

            } else {
                Toast.makeText(this, getString(R.string.Error_verification_code), Toast.LENGTH_SHORT).show();
            }
        }
    }
    /**
     * 倒计时
     */
    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tv_Countdown.setText(millisUntilFinished / 1000 + getString(R.string.Count_down));

        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onFinish() {
            tv_Countdown.setText(getString(R.string.Recapture_code));
            tv_Countdown.setTextColor(getColor(R.color.womain_pink));
            tv_Countdown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Verification_Code = getFourRandom();
                    getCode(Verification_Code);
                    tv_Countdown.setTextColor(getColor(R.color.black64));
                    timer.start();
                }
            });

        }
    };

    /**
     * 产生4位随机数(0000-9999)
     *
     * @return 6位随机数
     */
    public static String getFourRandom() {
        Random random = new Random();
        String fourRandom = random.nextInt(1000000) + "";
        int randLength = fourRandom.length();
        if (randLength < 6) {
            for (int i = 1; i <= 6 - randLength; i++)
                fourRandom = "0" + fourRandom;
        }
        return fourRandom;
    }

    /**
     * 请求第三方邮箱接口
     *
     * @param verification_Code
     */
    public void requestcode(String verification_Code) {
        retrofit = RetrofitUtil.getRetrofit();
        final SetMailRequest request = retrofit.create(SetMailRequest.class);
        Call<Mail> call = request.sendmail(Constants.APP_ID, toMail, Constants.FROM_MAIL, Constants.SUBJECT, getString(R.string.Mail_CODE1)+toMail+getString(R.string.Mail_CODE2)+verification_Code+getString(R.string.Mail_CODE3), Constants.APP_KEY);
        call.enqueue(new Callback<Mail>() {
            @Override
            public void onResponse(Call<Mail> call, Response<Mail> response) {

            }

            @Override
            public void onFailure(Call<Mail> call, Throwable t) {
                Toast.makeText(MailSignupCodeActivity.this, getString(R.string.Enclosed_please_find), Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void getCode(final String verification_Code) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                requestcode(verification_Code);
            }
        }).start();


    }

    private void signup(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject root= new JSONObject();
                try {
                    root.put("UserNo",  toMail);
                    root.put("UserPassword", md5(Password));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                final JSONObject out = GlobalHelper.PostData(root,"http://120.77.255.57/ting/register.php");
                try {
                    if (out.getInt("OperateResult")==1) {
                        Intent intent = new Intent("controlCenterActivity");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        String OperateMsg = out.getString("OperateMsg"); // 获取操作结果信息
                        System.out.printf(" OperateResult : %s \n OperateMsg : %s\n", out.getInt("OperateResult"), OperateMsg);
                        GUserNum =toMail;
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        System.out.println("predict error");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), getString(R.string.RegistrationFailed), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
                        }
                    });
                    e.printStackTrace();
                }
            }

        }).start();
    }
}
